# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy import signals
from scrapy.exporters import JsonLinesItemExporter


class JsonLinesPipeline(object):

    def __init__(self, ensure_ascii=False):
        self.files = {}

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(
            pipeline.spider_opened, signals.spider_opened)
        crawler.signals.connect(
            pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_opened(self, spider):
        file = open('data/%s_products.json' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporter = JsonLinesItemExporter(file, ensure_ascii=False)
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

# import json


# class TutorialPipeline(object):
#     def __init__(self):
#         self.file_tv = open(r'data/tv.json', 'a+', encoding='utf-8')
#         self.file_movie = open(r'data/movie.json', 'a+', encoding='utf-8')

#     def process_item(self, item, spider):
#         if spider.name == 'TV':
#             json.dump(dict(item), self.file_tv, sort_keys=True,
#                       indent=4, ensure_ascii=False)
#         elif spider.name == 'movie':
#             json.dump(dict(item), self.file_movie, sort_keys=True,
#                       indent=4, ensure_ascii=False)
#         return item

#     def close_spider(self):
#         pass
